package com.zhiqianbao.activity;

import android.app.ActivityGroup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.ApplyCouponInfo;
import com.zhiqianbao.entity.UpdateBean;
import com.zhiqianbao.service.UpdateService;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.WorthPurseUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

import static com.zhiqianbao.shared.SharedPreferanceUtils.initSharedData;

//import com.umeng.update.UmengUpdateAgent;

/**
 * Created by Liang on 2015/12/17.
 */
public class MainActivity extends ActivityGroup {
    public static final int DATA_FAILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();
    public static final String REFRESH_MSGS="com.mimidai.refresh.msgs";
    private TabHost tabHost;
    private TabWidget tabs;

    private RadioButton radioButtonApply;
    private RadioButton radioButtonAccount;
    private RadioButton radioButtonSetting;
    private RadioButton radioButtonMine;
    UpdateBean updateBean;
    private TextView viewMessagecenter;
    public int tabPosition = -1;//如果用户有借款未还，登录后直接跳转主页面的还款模块
    public static int sysMsgCounts = 0;//系统消息条数
    public static int customerCounts = 0;//客服中心条数
    private ButtonClickListener listener = new ButtonClickListener();
    private SharedPreferanceUtils sharedPreferanceUtils;
    private boolean aBoolean = false;
    String clickedIds = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_library_main);
        initView();
        initSharedData(this);
        checkExpressCoupon();
        //添加刷新消息提醒
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(REFRESH_MSGS);
        registerReceiver(refreshMsgReceiver,intentFilter);

    }


    private void initView() {
        radioButtonApply = (RadioButton) findViewById(R.id.radio_button_apply);
        radioButtonAccount = (RadioButton) findViewById(R.id.radio_button_account);
        radioButtonMine = (RadioButton) findViewById(R.id.radio_button_mine);
        radioButtonSetting = (RadioButton) findViewById(R.id.radio_button_setting);

        viewMessagecenter = (TextView) findViewById(R.id.view_messagecenter);

        radioButtonApply.setOnClickListener(listener);
        radioButtonAccount.setOnClickListener(listener);
        radioButtonMine.setOnClickListener(listener);
        radioButtonSetting.setOnClickListener(listener);

//

        radioButtonApply.setChecked(true);
        tabHost = (TabHost) findViewById(R.id.tabHost);
        tabHost.setup(this.getLocalActivityManager());
        //绑定借款页面
        TabHost.TabSpec specApply = tabHost.newTabSpec("apply");
        specApply.setIndicator(createApplyView());
        Intent intentApply = new Intent(this, ApplyTabHostActivity.class);
        specApply.setContent(intentApply);
        synchronized (MainActivity.this) {
            tabHost.addTab(specApply);
        }
        //绑定还款页面
        TabHost.TabSpec specAccount = tabHost.newTabSpec("account");
        specAccount.setIndicator(createAccountView());
        Intent intentAccount = new Intent(this, RepayTabHostActivity.class);
        specAccount.setContent(intentAccount);
        tabHost.addTab(specAccount);
        //绑定我的页面
        TabHost.TabSpec specSetting = tabHost.newTabSpec("setting");
        specSetting.setIndicator(createSettingView());
        Intent intentSetting = new Intent(this, SettingActivity.class);
        specSetting.setContent(intentSetting);
        tabHost.addTab(specSetting);
        //绑定更多页面
        TabHost.TabSpec specMine = tabHost.newTabSpec("mine");
        specMine.setIndicator(createMineView());
        Intent intentMine = new Intent(this, MineActivity.class);
        specMine.setContent(intentMine);
        tabHost.addTab(specMine);

        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("tabPosition")) {
            tabPosition = intent.getIntExtra("tabPosition", -1);
            switch (tabPosition) {
                case 2:
                    radioButtonAccount.setChecked(true);
                    tabHost.setCurrentTabByTag("account");
                    break;
                default:
                    tabHost.setCurrentTabByTag("apply");
                    radioButtonApply.setChecked(true);
                    if(intent.hasExtra("selectLogin")){
                        String selectLogin=intent.getStringExtra("selectLogin");
                        if("9".equals(selectLogin)){
                            Intent intent1 = new Intent(MainActivity.this,
                                    WorthPurseUtil.getZhiddActivity().getClass());
                            intent1.putExtra("login_state","9");
                            startActivity(intent1);
                            Toast.makeText(MainActivity.this,"您的账号在其他设备登录,请重新登录",
                                    Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                    break;
            }
            tabPosition = -1;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ab++;
        MobclickAgent.onResume(this);
        checkJumpFlag();
    }

    int ab = 0;

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(MainActivity.this, UpdateService.class);
        stopService(intent);
        unregisterReceiver(refreshMsgReceiver);
    }

    private void checkJumpFlag() {
        boolean isJump = SharedPreferanceUtils.getIsJumpFlag();
        if (isJump && tabHost != null) {
            radioButtonApply.setChecked(true);
            radioButtonAccount.setChecked(false);
            radioButtonMine.setChecked(false);
            radioButtonSetting.setChecked(false);
            tabHost.setCurrentTabByTag("apply");
            SharedPreferanceUtils.setJumpInfo(false, -1, -1);
        }
    }

    private View createApplyView() {
        View tabIndicator = (RelativeLayout) LayoutInflater.from(this).inflate(
                R.layout.activity_apply_tabhost, tabs, false);
        return tabIndicator;
    }

    private View createAccountView() {
        View tabIndicator = (RelativeLayout) LayoutInflater.from(this).inflate(
                R.layout.activity_repay_tabhost, tabs, false);
        return tabIndicator;
    }

    private View createSettingView() {
        View tabIndicator = (RelativeLayout) LayoutInflater.from(this).inflate(
                R.layout.activity_setting, tabs, false);
        return tabIndicator;
    }

    private View createMineView() {
        View tabIndicator = (RelativeLayout) LayoutInflater.from(this).inflate(
                R.layout.activity_mine, tabs, false);
        return tabIndicator;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);

    }

    class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (R.id.radio_button_account == v.getId()) {
                //还款
                if (Constants.LOGIN_USER != null) {
                    tabHost.setCurrentTabByTag("account");
                } else {
                    Intent loginIntent = new Intent(MainActivity.this,
                            WorthPurseUtil.getZhiddActivity().getClass());
                    startActivity(loginIntent);
                    finish();

                    radioButtonAccount.setChecked(false);
                    radioButtonApply.setChecked(true);
                    tabHost.setCurrentTabByTag("apply");
                }
            }
            else if (R.id.radio_button_apply == v.getId()) {
                //借款
                if (!tabHost.getCurrentTabTag().equals("apply")) {
                    checkExpressCoupon();
                }
                tabHost.setCurrentTabByTag("apply");
                radioButtonApply.setChecked(true);
            }
            else if (R.id.radio_button_mine == v.getId()){
                if (Constants.LOGIN_USER != null) {
                    tabHost.setCurrentTabByTag("setting");

                } else {
                    Intent loginIntent = new Intent(MainActivity.this,
                            WorthPurseUtil.getZhiddActivity().getClass());
                    startActivity(loginIntent);
                    finish();
                    radioButtonMine.setChecked(false);
                    radioButtonApply.setChecked(true);
                    tabHost.setCurrentTabByTag("apply");
                }
            }
            else if(R.id.radio_button_setting==v.getId()){
                    checkExpressCoupon();
                    tabHost.setCurrentTabByTag("mine");
                    radioButtonSetting.setChecked(true);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && intent.hasExtra("tabPosition")) {
            tabPosition = intent.getIntExtra("tabPosition", -1);
            switch (tabPosition) {
                case 2:
                    radioButtonAccount.setChecked(true);
                    tabHost.setCurrentTabByTag("account");
                    break;
                case 1:
                    tabHost.setCurrentTabByTag("apply");
                    radioButtonApply.setChecked(true);
                    break;
            }
        }
        tabPosition = -1;
        if (intent != null && intent.hasExtra("CLOSEALL") && intent.getBooleanExtra("CLOSEALL", false))
            finish();
    }

    public void checkExpressCoupon() {
        String idsText = null;
        try {
            idsText = FileUtils.getStrByFilename("ids.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.isBlank(idsText)) {
            String[] temp = idsText.split(":");
            if (temp.length == 1) {
                clickedIds = "";
            } else {
                clickedIds = idsText.split(":")[1];
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("ids", clickedIds);
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/checkNoAnnouncementNew",
                        mapParams, MainActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    ApplyCouponInfo data =gson.fromJson(result, ApplyCouponInfo.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }


    BroadcastReceiver refreshMsgReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkExpressCoupon();
        }
    };
    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FAILED:
                    Toast.makeText(MainActivity.this,Constants.HTTP_ERROR_MESSAGE,
                            Toast.LENGTH_SHORT).show();
                    break;
                case DATA_SCUESSFUL:
                    ApplyCouponInfo response = (ApplyCouponInfo) msg.obj;
                    if (response != null) {
                        if (response.getData() != null) {
                            int annCount = response.getData().getAnnCount();
                            int cusCount = response.getData().getCusCount();
                            int sysCount = response.getData().getSysCount();
                            //保存未读公告个数
                            SharedPreferanceUtils sharedPreferanceUtils = new SharedPreferanceUtils(MainActivity.this);
                            sharedPreferanceUtils.setNoannouncementCounts(annCount);
                            int count = annCount + cusCount + sysCount;
                            if (count == 0) {
                                viewMessagecenter.setVisibility(View.GONE);
                            } else {
                                viewMessagecenter.setVisibility(View.VISIBLE);
                                viewMessagecenter.setText(count + "");
                            }
                        }
                    }
                    break;
            }

        }
    };


}
